﻿using System;
using System.Collections.Generic;
using System.Web;


namespace CCPSIP.Group
{
    /// <summary>CCPSIP_049：聊天群組重新命名 API</summary>
    /// idHeader = 裝置 UUID 前八碼。
    /// checkcode = 裝置限時驗證碼。
    /// GroupID = Client端的群組ID，字串。
    /// GroupName = 新的群組名稱。
    /// 註：只有 群組管理員(Host) 可以執行重新命名。

    public class rename_group : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";


            try
            {
                //【01】取得POST參數，驗證身分
                //
                string idHeader = req.Form["idHeader"];
                string checkcode = req.Form["checkcode"];
                string ClientGID = req.Form["GroupID"];  //Client端的群組ID
                string GroupName = req.Form["GroupName"];//新的群組名稱

                SipUserInfo userInfo = SipKit.GetUserInfo(idHeader, checkcode, req);
                if (userInfo == null)
                {
                    throw new Exception("Error_01: Cannot identify this device");//無法識別此裝置
                }

                if (string.IsNullOrEmpty(GroupName))
                {
                    throw new Exception("Error_02: Grout name cannot be empty");
                }


                //【02】檢查User是否為群組管理員
                //
                bool isHost = OracleKitGroup.isHostOfGroup(userInfo.SIP_Num, ClientGID);
                if (!isHost)
                {
                    throw new Exception("Error_03: You are not the group host");//不是群組管理員
                }


                //【03】重新命名群組
                //
                OracleKitGroup.RenameGroup(userInfo.SIP_Num, ClientGID, GroupName);


                //【98】通知Push Service
                //
                PushKit.WakePushAsync(PushKit.PushType.Msg);


                //【99】回傳結果
                //
                resultStr = "OK";
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                resultStr = ChrisKit.Ex2Xml(ex, false);
            }
            finally
            {
                int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
                resp.Flush();
                resp.Close();
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}
